import React, { Fragment } from 'react'
import { View, StyleSheet, FlatList, Text, Animated, Easing } from 'react-native'
import { connect } from 'react-redux'
import { ScaleS, ScaleT, IS_IOS, WIDTH, IS_IPHONEX } from 'src/utils/ScreenUtil'
import BasePage from 'src/pageP/base/base-page/index'
import { UPDATE_USERINFO_ACTION } from 'src/store/actions/userinfo'
import CustomImage from 'src/components/image/CustomImage'
import JobIntentionCardNew from 'src/components/card-job-intention-new'
import EducationInfoCardNew from 'src/components/card-education-info-new'
import WorkExperienceCardNew from 'src/components/card-work-experience-new'
import { getGenderChinese, fixImageUrls } from 'src/utils/ConfigUtil'
import { getAge } from 'src/utils/TimeUtil'
import { defaultPortraitGray, getJobStatus, getUserAvatorLocalCByGender } from '../../../utils/ConfigUtil'
import { DO_REQUEST_MAIN_PAGE_C_ACTION } from '../mine-page/store/action'
import { DO_REQUEST_USERINFO_C_ACTION } from '../../../store/actions/userinfo'
import IMController from 'src/utils/IMController'
import CustomButton from '../../../components/button/CustomButton'
import BlockBtn from 'src/components/button/BlockBtn'
import { UPDATEIM } from '../../../store/types/im'
import {
  findUserArchiveByArchiveId, inRecruitPostNameCategoryList,
  insertArchiveCollection,
  removeArchiveCollection,
  talentTalk,
  talentTalkTime,
  myCenterNumbers,
  blackUser,
  findUserActiveTime
} from '../../../utils/RequestAPI'
import { CommonToast, DismissLoading, ShowLoading } from '../../../utils/ToastUtil'
import CollectionBtn from '../../../components/button/CollectionBtn'
import { isEnv } from 'src/config/index'
import { showTipModal } from 'src/utils/ModalUtil'
import DefaultImage from '../../../components/image/DefaultImage'
import { shareToWXMiniProgram } from 'src/utils/PayUtil'
import ShareBtn from 'src/components/button/ShareBtn'
import { showImageViewerModal } from '../../../utils/ModalUtil'
import { ImageHost } from '../../../config/index'
import NavigationUtil from 'src/utils/NavigationUtil'
import { TabBar, TabView } from 'react-native-tab-view'
import { ONE_PIXEL } from '@/utils/ScreenUtil'

// 发送行为
const mapDispatchToProps = dispatch => ({
  updateUserInfo(payload) {
    dispatch(UPDATE_USERINFO_ACTION(payload))
  },
  updateImState(payload) {
    dispatch({
      type: UPDATEIM,
      payload: {
        ...payload
      }
    })
  }
})

@connect(({ CMineCenterStore, userinfo, im, BMineCenterStore }) => ({
  jobHuntingModels: CMineCenterStore.jobHuntingModels,
  educations: CMineCenterStore.educations,
  userArchiveWorkModels: CMineCenterStore.userArchiveWorkModels,
  userArchiveImgModels: CMineCenterStore.userArchiveImgModels,
  userinfoC: userinfo.C,
  userinfoB: userinfo.B,
  intro: CMineCenterStore.intro,
  userArchiveModel: CMineCenterStore.userArchiveModel,
  myCenterNumbersNew: CMineCenterStore.myCenterNumbers,
  userinfo,
  isBlack: BMineCenterStore.company.isBlack,
  companyId: BMineCenterStore.haveCompanyApply.companyId,
  companyDone: BMineCenterStore.haveCompanyApply.companyDone,
  isVip: BMineCenterStore.member.remainingDay > 0,
  ...im
}), mapDispatchToProps)
class CResumeDetail extends BasePage {
  constructor(props) {
    super(props)
    const { navigation: { state: { params: { userId, showCommunicate = true, type, postId } = {} } } } = this.props
    this.userId = userId
    this.type = type
    this.postId = postId
    this.showCommunicate = showCommunicate
    this.state = {
      header: {},
      collectionId: false,
      scrollY: new Animated.Value(0),
      resumeDetail: this._generateResumeDetail(),
      talkTime: 0,
      showPortrait: !this.userId,
      myCenterNumbers: props.myCenterNumbersNew || {},
      index: 0,
      routes: [
        { key: 'resume', title: '简历' },
        // { key: 'schoolEnrollment', title: '校招' },
        { key: 'alumnus', title: '校友' }
      ],
      scrollBeginState: false,
      scrollBeginY: 0,
      scrollRange: 5,
      logoShow: false,
      scrollChat: new Animated.Value(0),
      showBottomBtnHeight: 200,
      showBottomBtn: false,
      userActiveTime: ''
    }
    this.userActiveTimeList = { '1h': '一小时内', '2h': '两小时内', '4h': '四小时内', '1d': '一天内', '3d': '三天内', '1w': '一周内', '1m': '一个月内', '3m': '三个月内' }
    this.logoAnimatedValue = new Animated.Value(0)
    this.bottomBtnValue = new Animated.Value(0)
  }

  _generateResumeDetail = () => {
    const {
      jobHuntingModels, userArchiveImgModels, userArchiveWorkModels, educations, intro, userinfoC, userArchiveModel
    } = this.props
    if (this.userId) {
      return {
        userAvatorSource: null,
        userinfoC: {},
        intro: null,
        jobHuntingModels: [],
        userArchiveModel: {},
        userArchiveWorkModels: [],
        userArchiveImgModels: [],
        educations: []
      }
    } else {
      return {
        jobHuntingModels,
        userArchiveImgModels,
        userArchiveWorkModels,
        educations,
        intro,
        userinfoC,
        userArchiveModel,
        userAvatorSource: userinfoC.userAvator
      }
    }
  }

  getUserInfo = async () => {
    const userinfo = await DO_REQUEST_USERINFO_C_ACTION({
      params: {
        userId: this.userId
      }
    }).payload
    const mainPage = await DO_REQUEST_MAIN_PAGE_C_ACTION({
      params: {
        userId: this.userId
      }
    }).payload
    return {
      userinfoC: userinfo.C,
      userAvatorSource: userinfo.C.userAvator,
      ...mainPage
    }
  }

  componentDidMount() {
    console.log('componentDidMount')
    // super.componentDidMount()
  }

  componentDidFocus() {
    console.log('componentDidFocus')
  }

  componentWillFocus() {
    console.log('componentWillFocus')
    if (this.userId) {
      findUserActiveTime({ params: { userId: this.userId } }).then((data) => {
        this.setState({
          userActiveTime: data.data
        })
      })
      ShowLoading()
      this.getUserInfo().then((data) => {
        DismissLoading()
        this.setState({
          resumeDetail: data,
          showPortrait: true
        }, () => {
          this.getCenterNumbers()
        })
        this.findIsCollection(data)
        // 创建网易云信账号
        console.log(data, 'data')
        this.createWyAccount(data)
      }).catch(() => {
        DismissLoading()
      })
      const { companyId } = this.props
      companyId && talentTalkTime({ params: { companyId } }).then((data) => {
        this.setState({
          talentTalkTime: data.data
        })
      })
    }
  }

  /* 请求个人中心数据量 */
  getCenterNumbers = () => {
    const { resumeDetail: { userinfoC: { userId }, archiveInfo: { archiveId } } = {} } = this.state
    return new Promise((resolve, reject) => {
      myCenterNumbers({ params: { type: 'C' }, headers: { userId, archiveId } }).then(res => {
        if (res.code === 200) {
          this.setState({
            myCenterNumbers: res.data
          })
          resolve({ myCenterNumbers: res.data })
        } else {
          reject(res)
        }
      })
    })
  }

  /**
   * 查询简历是否被收藏
   */
  findIsCollection = (resumeDetail) => {
    const {
      archiveInfo: { archiveId }
    } = resumeDetail
    const { userinfoB: { userId } = {} } = this.props
    if (!userId) return
    findUserArchiveByArchiveId({
      params: {
        archiveId,
        userId
      }
    }).then((data) => {
      console.info(data)
      const { data: { archiveId, postId } = {} } = data
      if (archiveId) {
        this.setState({
          collectionId: archiveId
        })
      }
      if (postId) {
        this.postId = postId
      }
    })
  }

  createWyAccount = resumeDetail => {
    // 创建网易云信账号
    const {
      userinfoC: { userId, userName, userAvator, gender, mobile }
    } = resumeDetail
    const identifier = userId + 'c' + isEnv
    const userInfo = {
      userName,
      userAvator,
      userId,
      gender,
      mobile
    }
    if (userId) {
      IMController.createAccount({
        userId: identifier,
        role: 'C',
        userInfo
      }).then(() => {
        console.log(this.props.selToID, 'toididid')
      })
    }
  }

  renderNavigationBarChild = () => {
    const { resumeDetail: { userinfoC } = {}, collectionId, scrollY } = this.state
    return (
      <Fragment>
        <Animated.Image
          style={[
            styles.navigationImage,
            {
              opacity: scrollY.interpolate({
                inputRange: [0, 30, 31],
                outputRange: [0, 0, 1]
              })
            }
          ]}
          source={{ uri: fixImageUrls(userinfoC.userAvator) }}
        >
        </Animated.Image>
        {/* {!!this.userId && <View style={styles.navigationBar}>
          <ShareBtn onPress={this._onShared} />
          <CollectionBtn isCollected={!!collectionId} onCollected={this._onCollected} />
        </View>} */}
        <View style={[styles.navigationBar, { right: ScaleS(40) }]}>
          <BlockBtn onPress={this._onBlockClick} />
        </View>
        <View style={styles.navigationBar}>
          <ShareBtn onPress={this._onShared} />
        </View>
      </Fragment>
    )
  }

  _onShared = () => {
    const { resumeDetail: { userinfoC: { userName: title, userId } } = {} } = this.state
    if (userId && title) {
      shareToWXMiniProgram({ title, shareUrl: `pages/person-detail/index?userId=${userId}&share=app` })
    }
  }

  _onBlockClick = () => {
    if (this._loginJump()) {
      return
    }
    const onConfirm = () => {
      const { userinfoB: { userId: bUserId },
        navigation: {
          state: {
            params: { blockCallback }
          }
        } } = this.props
      const { resumeDetail: { userinfoC: { userId: cUserId } } = {} } = this.state
      blackUser({ params: { bUserId, cUserId } }).then(() => {
        blockCallback()
        this.tipPrompModal.close(() => {
          this.goBack()
          this.tipPrompModal = null
        })
      })
    }
    this.tipPrompModal = showTipModal({
      titleText: '屏蔽提示',
      contentText: '是否要屏蔽该人才？屏蔽后该人才将不再显示',
      confirmText: '确定',
      onCancel: () => {
        this.tipPrompModal.close()
      },
      onConfirm
    })
  }

  _onCollected = (isCollected) => {
    const { userinfo: { role } } = this.props
    if (role === 'B') {
      if (!this._loginJump()) {
        if (isCollected) {
          this.unFavoriteClick()
        } else {
          this.favoriteClick()
        }
      }
    }
  }

  // 收藏
  favoriteClick = () => {
    if (parseInt(this.postId) >= 0) {
      this._insertArchiveCollection(this.postId)
    } else if (parseInt(this.type) >= 0) {
      this._checkPost((defaultPost) => {
        this._insertArchiveCollection(defaultPost.postId)
      })
    } else {
      this._insertArchiveCollection()
    }
  }

  /**
   * 插入收藏
   * @param postId
   * @private
   */
  _insertArchiveCollection = (postId) => {
    const { resumeDetail: { archiveInfo } = {} } = this.state
    if (!archiveInfo || !archiveInfo.archiveId) {
      return
    }
    const { userinfoB: { userId } } = this.props
    const params = {
      archiveId: archiveInfo.archiveId,
      userId
    }
    if (postId) {
      params.postId = postId
    }
    insertArchiveCollection({
      params
    }).then(() => {
      CommonToast('收藏成功')
      this.getCenterNumbers()
      this.setState({
        collectionId: archiveInfo.archiveId
      })
    })
  }

  // 取消收藏
  unFavoriteClick = () => {
    const { collectionId } = this.state
    const { userinfoB: { userId } } = this.props
    removeArchiveCollection({
      params: {
        ids: collectionId.toString(),
        userId
      }
    }).then(() => {
      CommonToast('取消收藏成功')
      this.getCenterNumbers()
      this.setState({
        collectionId: null
      })
    })
  }

  goJobCollection = () => {
    // const { resumeDetail: { userinfoC: { userId } } = {} } = this.state
    // this.props.navigation.navigate('CJobCollection', {
    //   userId
    // })
  }

  _onScroll = (event) => {
    const { scrollBeginState, scrollBeginY, scrollRange, logoShow, showBottomBtn, showBottomBtnHeight } = this.state
    const {
      contentOffset: { y = 0 } = {}
    } = event.nativeEvent
    // 展示底部沟通按钮
    if (y > showBottomBtnHeight && !showBottomBtn) {
      this.setState({
        showBottomBtn: true
      })
    } else if (y <= showBottomBtnHeight && showBottomBtn) {
      this.setState({
        showBottomBtn: false
      })
    }
    // 展示底部沟通按钮上面的图片
    // if (scrollBeginState) {
    //   const minus = y - scrollBeginY
    //   if (Math.abs(minus) >= scrollRange) {
    //     if (minus > 0 && logoShow) {
    //       this.setState({
    //         logoShow: false
    //       })
    //       this.hideLogo()
    //     } else if (minus < 0 && !logoShow) {
    //       this.setState({
    //         logoShow: true
    //       })
    //       this.showLogo()
    //     }
    //   }
    // }
  }

  _onMomentumScrollEnd = event => {
    const { logoShow } = this.state
    const {
      contentOffset: { y = 0 } = {},
      contentSize: { height: contentSizeHeight },
      layoutMeasurement: { height: oriageScrollHeight }
    } = event.nativeEvent
    if (y + oriageScrollHeight < contentSizeHeight && logoShow) {
      this.setState({
        logoShow: false
      })
      this.hideLogo()
    } else if (y + oriageScrollHeight >= contentSizeHeight && !logoShow) {
      this.setState({
        logoShow: true
      })
      this.showLogo()
    }
  }

  _onScrollBeginDrag = (event) => {
    // const { contentOffset: { y = 0 } = {} } = event.nativeEvent
    // this.setState({
    //   scrollBeginState: true,
    //   scrollBeginY: y
    // })
  }

  _onScrollEndDrag = (event) => {
    // this.setState({
    //   scrollBeginState: false
    // })
    this._onMomentumScrollEnd(event)
  }

  showLogo = () => {
    // 展示底部按钮上面的图片
    this.logoAnimatedValue.setValue(0)
    Animated.timing(this.logoAnimatedValue, {
      toValue: 1,
      duration: 500,
      easing: Easing.ease
    }).start()
  }

  hideLogo = () => {
    // 隐藏底部按钮上面的图片
    this.logoAnimatedValue.setValue(1)
    Animated.timing(this.logoAnimatedValue, {
      toValue: 0,
      duration: 500,
      easing: Easing.ease
    }).start(() => {
      this.setState({
        logoShow: false
      })
    })
  }

  childRender() {
    const {
      collectionId,
      resumeDetail: {
        userinfoC, userArchiveModel
      } = {}, showPortrait,
      myCenterNumbers,
      showBottomBtn,
      logoShow,
      userActiveTime
    } = this.state
    return (
      <View style={styles.container}>
        <Animated.ScrollView contentContainerStyle={styles.scrollView} style={styles.container}
          showsVerticalScrollIndicator={false}
          onScroll={
            Animated.event([{
              nativeEvent: { contentOffset: { y: this.state.scrollY } }
            }], {
              useNativeDriver: IS_IOS,
              listener: this._onScroll
            })}
          onScrollBeginDrag={this._onScrollBeginDrag}
          onScrollEndDrag={this._onScrollEndDrag}
          onMomentumScrollEnd={this._onMomentumScrollEnd}
        >
          <View style={styles.title}>
            <View style={styles.titleRight}>
              <Text style={styles.titleRightTop}>{userinfoC.userName}</Text>
              <Text style={styles.titleRightBottom}>
                {userinfoC.gmtBorth && `${getGenderChinese(userinfoC.gender)}·${getAge(userinfoC.gmtBorth)}岁  ${userArchiveModel && getJobStatus(userArchiveModel.jobStatus)}`}
              </Text>
            </View>
            {
              showPortrait ? (
                <DefaultImage
                  style={styles.portraitImg}
                  source={{ uri: userinfoC.userAvator }}
                  errorSource={getUserAvatorLocalCByGender(userinfoC.gender, userinfoC.userId)} />
              ) : (
                  <CustomImage source={defaultPortraitGray} style={styles.portraitImg} />
                )
            }
          </View>
          <View style={styles.infoContainer}>
            <View style={styles.infoContainerLeft}>
              <CustomButton style={styles.followInfo} onPress={this.goJobCollection}>
                <Text style={styles.followInfoTop}>{myCenterNumbers.postCollection || 0}</Text>
                <Text style={styles.followInfoBottom}>关注</Text>
              </CustomButton>
              <CustomButton style={styles.followInfo}>
                <Text style={styles.followInfoTop}>{myCenterNumbers.archiveCollection || 0}</Text>
                <Text style={styles.followInfoBottom}>被关注</Text>
              </CustomButton>
            </View>
            <View style={styles.infoContainerRight}>
              <CustomButton style={styles.followBtn} params={!!collectionId} onPress={this._onCollected}>
                {collectionId
                  ? <CustomImage style={styles.itemCloseImg} source={require('@/imgC/userinfo/icon_white_ok.png')} />
                  : <Text style={styles.followBtnText}>+</Text>}

              </CustomButton>
              <CustomButton style={styles.goChatBtn} onPress={this.goChat}>
                <Text style={styles.goChatBtnText}>沟通</Text>
              </CustomButton>
            </View>
          </View>

          <TabView
            style={styles.tabView}
            navigationState={this.state}
            renderScene={this._renderScene}
            onIndexChange={this._onIndexChange}
            renderTabBar={this._renderTabBar}
          />
        </Animated.ScrollView>

        {
          !!this.userId && !!userinfoC.userId && !!this.showCommunicate && !!showBottomBtn && (
            <View style={styles.communicateContainer}>
              {logoShow && <Animated.View style={[styles.communicateLogo, { opacity: this.logoAnimatedValue }]}>
                <CustomImage style={styles.communicateLogoImg} source={require('@/imgC/post/postDetail.png')} />
              </Animated.View>}
              <View style={styles.communicateOutView}>
                <View style={styles.activeTime}>
                  <View style={styles.activeTimeDot}></View>
                  <Text style={styles.activeTimeText}>{userActiveTime ? this.userActiveTimeList[userActiveTime] : '三个月内'}活跃 </Text>
                </View>
                <CustomButton style={styles.communicateView} onPress={this.goChat}>
                  <Text style={styles.communicateLabel}>沟通</Text>
                </CustomButton>
              </View>
            </View>
          )
        }
      </View>
    )
  }

  /**
   * 渲染每一个屏
   * @param route
   * @param jumpTo
   * @returns {*}
   * @private
   */
  _renderScene = ({ route, jumpTo }) => {
    switch (route.key) {
      case 'resume':
        return this._renderResumeComponent()
      // case 'schoolEnrollment':
      //   return this._renderSchoolEnrollmentComponent()
      case 'alumnus':
        return this._renderalumnusComponent()
    }
  }

  /**
   * 渲染简历
   * @returns {*}
   * @private
   */
  _renderResumeComponent = () => {
    const {
      resumeDetail: {
        jobHuntingModels, userArchiveImgModels, userArchiveWorkModels, educations, intro
      } = {}
    } = this.state
    return (
      <Fragment>
        <View style={styles.jobIntentionView}>
          <View style={styles.rightIcon}>
            <CustomImage
              style={styles.rightIconText}
              source={require('@/imgC/userinfo/icon_i.png')}
            />
          </View>
          <View style={styles.jobIntentionTitleView}>
            <Text style={styles.jobIntentionTitleLabel}>求职意向</Text>
            {
              jobHuntingModels && jobHuntingModels.length > 0 && jobHuntingModels.map((item, index) => {
                return (<JobIntentionCardNew
                  key={item.id}
                  style={{ marginTop: ScaleS(index === 0 ? 0 : 35) }}
                  dataSource={item} />)
              })
            }
          </View>
        </View>

        <View style={styles.jobIntentionView}>
          <View style={styles.rightIcon}>
            <CustomImage
              style={styles.rightIconText}
              source={require('@/imgC/userinfo/icon_a.png')}
            />
          </View>
          <View style={styles.selfAssessmentTitleView}>
            <Text style={styles.selfTitleLabel}>自我评价</Text>
            <Text style={styles.selfAssessmentContent}>{intro || '这个家伙很懒,什么都没写'}</Text>
          </View>
        </View>

        {
          educations.length > 0 && (
            <View style={styles.jobIntentionView}>
              <View style={styles.rightIcon}>
                <CustomImage
                  style={styles.rightIconText}
                  source={require('@/imgC/userinfo/icon_e.png')}
                />
              </View>
              <View style={styles.jobIntentionTitleView}>
                <Text style={styles.jobIntentionTitleLabel}>教育信息</Text>
                {
                  educations.map((item, index) => {
                    return (<EducationInfoCardNew
                      key={item.id}
                      style={{ marginTop: ScaleS(index === 0 ? 0 : 30) }}
                      dataSource={item} />)
                  })
                }
              </View>
            </View>
          )
        }

        {
          userArchiveWorkModels.length > 0 && (
            <View style={styles.jobIntentionView}>
              <View style={styles.rightIcon}>
                <CustomImage
                  style={styles.rightIconText}
                  source={require('@/imgC/userinfo/icon_w.png')}
                />
              </View>
              <View style={styles.jobIntentionTitleView}>
                <Text style={styles.jobIntentionTitleLabel}>工作经验</Text>
                {
                  userArchiveWorkModels.map((item, index) => {
                    return (<WorkExperienceCardNew
                      key={item.id}
                      style={{ marginTop: ScaleS(index === 0 ? 0 : 30) }}
                      dataSource={item} />)
                  })
                }
              </View>
            </View>
          )
        }

        {
          userArchiveImgModels.length > 0 && (
            <Fragment>
              <View style={styles.jobIntentionView}>
                <View style={styles.rightIcon}>
                  <CustomImage
                    style={styles.rightIconText}
                    source={require('@/imgC/userinfo/icon_p.png')}
                  />
                </View>
                <View style={styles.photoView}>
                  <Text style={styles.jobIntentionTitleLabel}>我的相册</Text>
                  <View style={styles.photoAlbumScrollView}>
                    {!!userArchiveImgModels && userArchiveImgModels.length > 0 && <FlatList
                      style={styles.photoAlbumScrollView}
                      data={userArchiveImgModels}
                      horizontal={false}
                      numColumns={3}
                      renderItem={this._renderItem}
                      keyExtractor={this._keyExtractor} />}
                    {/* {
                      userArchiveImgModels.map((item, index) => (
                        <CustomButton key={index} params={index} onPress={this._showImageViewer}>
                          <CustomImage
                            style={[styles.photoImg, { marginRight: index % 3 === 2 ? 0 : ScaleS(4) }]}
                            source={{ uri: item.imgUrl }}/>
                        </CustomButton>
                      ))
                    } */}
                  </View>
                </View>
              </View>
            </Fragment>
          )
        }
      </Fragment>
    )
  }

  /**
   * 渲染校招
   * @returns {*}
   * @private
   */
  _renderSchoolEnrollmentComponent = () => {
    return (
      <Fragment></Fragment>
    )
  }

  /**
   * 渲染校友
   * @returns {*}
   * @private
   */
  _renderalumnusComponent = () => {
    return (
      <Fragment></Fragment>
    )
  }

  /**
   * 切换标签
   * @param index
   * @private
   */
  _onIndexChange = (index) => {
    this.setState({ index })
  }

  /**
   * 渲染tabBar
   * @param props
   * @returns {*}
   * @private
   */
  _renderTabBar = (props) => {
    const { navigationState: { index, routes } } = props
    return (
      <View style={styles.tabContainer}>
        <CustomButton style={styles.tabItem} onPress={this._tabBarClick} params={{ props, key: routes[0].key }}>
          <Text style={[styles.tabItemText, index === 0 && styles.tabItemActive]}>{routes[0].title}</Text>
        </CustomButton>
        {/* <View style={styles.tabLine}></View>
        <CustomButton style={styles.tabItem} onPress={this._tabBarClick} params={{ props, key: routes[1].key }}>
          <Text style={[styles.tabItemText, index === 1 && styles.tabItemActive]}>{routes[1].title}</Text>
        </CustomButton> */}
        <View style={styles.tabLine}></View>
        <CustomButton style={styles.tabItem} onPress={this._tabBarClick} params={{ props, key: routes[1].key }}>
          <Text style={[styles.tabItemText, index === 1 && styles.tabItemActive]}>{routes[1].title}</Text>
        </CustomButton>
      </View>
    )
  }

  _tabBarClick = ({ props, key }) => {
    // const { jumpTo, navigationState: { index, routes } } = props
    // jumpTo(key)
  }

  _renderItem = ({ item, index }) => {
    return (
      <CustomButton
        style={[styles.itemView, { marginRight: index % 3 === 2 ? 0 : ScaleS(4) }]}
        params={{ item, index }}
        onPress={this._showImageViewer}
      >
        <CustomImage
          style={styles.photoImg}
          source={{ uri: item.imgUrl }} />
      </CustomButton>
    )
  }

  _keyExtractor = item => item.id

  _showImageViewer = ({ index }) => {
    const { resumeDetail: { userArchiveImgModels } } = this.state
    if (!this.imageDataArr) {
      this.imageDataArr = userArchiveImgModels.map((item) => {
        item.url = ImageHost + item.imgUrl
        return item
      })
    }
    this.imgageViewerModal = showImageViewerModal({
      onClose: this._closeImageViewerModal,
      images: this.imageDataArr,
      initIndex: index
    })
  }

  _closeImageViewerModal = () => {
    if (this.imgageViewerModal) {
      this.imgageViewerModal.close()
    }
  }

  goChat = () => {
    // 点击立即沟通
    const { isVip, userinfo: { role } } = this.props
    const { talentTalkTime } = this.state
    this.props.updateImState({
      msgArray: []
    })
    if (role === 'B' && !this._loginJump()) {
      if (isVip) {
        // 判断是否发布了岗位，如果发布了，就去聊天，否则应该去发布岗位
        this._goChatPageB()
      } else {
        if (talentTalkTime > 0) {
          const modal = showTipModal({
            titleText: '提示',
            contentText: `非会员拥有3次免费沟通机会，你已经沟通过${3 - Math.max(talentTalkTime, 0)}次${
              talentTalkTime > 0 ? `，还有${talentTalkTime}次免费沟通机会` : ''
              }`,
            confirmText: '沟通',
            cancelText: '升级会员',
            onConfirm: () => {
              this._getPostId().then(postId => {
                talentTalk({
                  params: {
                    type: 'B',
                    cmpUserId: this.userId,
                    companyId: this.props.companyId,
                    userId: this.props.userinfoB.userId,
                    postId
                  }
                }).then(() => {
                  this.props.navigation.navigate('ChatPageB', {
                    postId
                  })
                })
              })
              modal.close()
            },
            onCancel: () => {
              this.props.navigation.navigate('BMemberOpen')
              modal.close()
            }
          })
        } else {
          const modal = showTipModal({
            titleText: '提示',
            contentText: '您当前为企业非会员用户，3次免费沟通已用完。成为会员用户，拥有超多会员权限哦～',
            confirmText: '升级会员',
            cancelText: '取消',
            onConfirm: () => {
              this.props.navigation.navigate('BMemberOpen')
              modal.close()
            },
            onCancel: () => {
              modal.close()
            }
          })
        }
      }
    }
  }

  _getPostId = () => {
    // 获取postId
    return new Promise(resolve => {
      if (parseInt(this.postId) >= 0) { // 没有传递的
        resolve(this.postId)
      } else if (parseInt(this.type) >= 0) { // 传递过来了
        this._checkPost((defaultPost) => {
          resolve(defaultPost.postId)
        })
      } else {
        resolve()
      }
    })
  }

  _goChatPageB = () => {
    this._getPostId().then(postId => {
      this._talentTalkToChatPage(postId)
    })
  }

  /**
   * 检测是否有岗位
   * @param successCallback
   * @private
   */
  _checkPost = (successCallback) => {
    const { companyId } = this.props
    ShowLoading()
    inRecruitPostNameCategoryList({
      headers: { companyId },
      params: { type: this._getPostTypeByType() }
    }).then((data) => {
      if (data.data.length <= 0) { // 没有发布职位
        this._goPublishPost()
        return
      }
      const defaultPost = data.data.find((item) => {
        return item.isDefault
      })
      this.postId = defaultPost.postId
      successCallback && successCallback(defaultPost)
    }).finally(() => {
      DismissLoading()
    })
  }

  _talentTalkToChatPage = (postId) => {
    const params = {
      type: 'B',
      cmpUserId: this.userId,
      companyId: this.props.companyId,
      userId: this.props.userinfoB.userId
    }
    if (postId) {
      params.postId = postId
    }
    talentTalk({
      params
    }).then(() => {
      NavigationUtil.navigate('ChatPageB', {
        postId
      })
    })
  }

  /**
   * 去发布岗位
   * @private
   */
  _goPublishPost = () => {
    const onPostConfirm = () => {
      this.postModal.close(() => {
        this.postModal = null
        NavigationUtil.navigate('JobPartTime', { type: this._getPostTypeByType() })
      })
    }
    const onPostCancel = () => {
      this.postModal.close(() => {
        this.postModal = null
      })
    }
    this.postModal = showTipModal({
      titleText: '提示',
      contentText: `还没有正在招聘的${this._getPostNameByType()}岗位`,
      confirmText: '去发布岗位',
      cancelText: '取消',
      onConfirm: onPostConfirm,
      onCancel: onPostCancel
    })
  }

  _getPostNameByType = () => {
    switch (this.type) {
      case 0:
        return '兼职'
      case 1:
        return '实习'
      case 2:
        return '全职'
    }
  }

  _getPostTypeByType = () => {
    switch (this.type) {
      case 0:
        return 0
      case 1:
        return 2
      case 2:
        return 1
    }
  }

  _loginJump = () => {
    const {
      userinfo: { userId, B: { userId: userIdB } = {} },
      companyDone,
      isBlack
    } = this.props
    if (!userId) {
      this.props.navigation.navigate('OneLogin')
      return true
    }
    if (!userIdB) {
      this.props.navigation.navigate('BFirstUserInfo')
      return true
    }
    if (isBlack) {
      CommonToast('您的企业已被拉黑')
      return true
    }
    if (!companyDone) {
      CommonToast('请完成审核').then(() => {
        this.props.navigation.navigate('BMinePage')
      })
      return true
    }
  }
}

export default CResumeDetail

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  scrollView: {
    paddingBottom: ScaleS(30)
  },
  title: {
    paddingHorizontal: ScaleS(20),
    flexDirection: 'row',
    alignItems: 'flex-start',
    paddingTop: ScaleS(30)
  },
  portraitImg: {
    width: ScaleS(90),
    height: ScaleS(90),
    resizeMode: 'cover',
    borderRadius: ScaleS(45)
  },
  titleRight: {
    flex: 1,
    alignItems: 'flex-start'
  },
  titleRightTop: {
    color: '#3C3C3C',
    fontSize: ScaleT(27),
    fontWeight: '700'
  },
  titleRightBottom: {
    color: '#3C3C3C',
    fontSize: ScaleT(14),
    fontWeight: '400',
    marginTop: ScaleS(20)
  },
  infoContainer: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginTop: ScaleS(50),
    marginHorizontal: ScaleS(20),
    paddingBottom: ScaleS(20),
    borderBottomColor: '#f1f1f1',
    borderBottomWidth: ONE_PIXEL,
    borderStyle: 'solid'
  },
  infoContainerLeft: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  followInfo: {
    flexDirection: 'column',
    alignItems: 'center',
    marginRight: ScaleS(40)
  },
  followInfoTop: {
    fontSize: ScaleT(20),
    fontWeight: 'bold',
    color: '#3C3C3C'
  },
  followInfoBottom: {
    fontSize: ScaleT(11),
    color: '#9E9E9E',
    marginTop: ScaleS(5)
  },
  infoContainerRight: {
    flexDirection: 'row'
  },
  followBtn: {
    width: ScaleS(50),
    height: ScaleS(30),
    backgroundColor: 'rgba(74,74,74,1)',
    borderRadius: ScaleS(4),
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: ScaleS(10)
  },
  followBtnText: {
    fontSize: ScaleT(18),
    fontWeight: 'bold',
    color: '#fff'
  },
  goChatBtn: {
    width: ScaleS(70),
    height: ScaleS(30),
    backgroundColor: 'rgba(255,228,0,1)',
    borderRadius: ScaleS(4),
    justifyContent: 'center',
    alignItems: 'center'
  },
  goChatBtnText: {
    fontSize: ScaleT(12),
    fontWeight: '500',
    color: '#000'
  },
  selfAssessmentTitleView: {
    flex: 1
  },
  selfAssessmentContent: {
    color: '#818181',
    fontSize: ScaleT(14),
    fontWeight: '300',
    lineHeight: ScaleT(28)
  },
  jobIntentionView: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'flex-start',
    marginHorizontal: ScaleS(20),
    marginTop: ScaleS(30)
  },
  jobIntentionTitleView: {
    flex: 1,
    flexDirection: 'column',
    paddingBottom: ScaleS(28),
    borderBottomColor: 'rgba(151, 151, 151, 0.25)',
    borderBottomWidth: ONE_PIXEL,
    borderStyle: 'solid'
  },
  photoView: {
    flex: 1,
    flexDirection: 'column',
    paddingBottom: ScaleS(30)
  },
  jobHuntingTop: {
    width: '100%',
    height: ScaleS(22),
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: ScaleS(22)
  },
  selfAssessmentTitleTop: {
    marginBottom: ScaleS(14)
  },
  jobIntentionTitleLabel: {
    width: '100%',
    height: ScaleS(22),
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: ScaleS(22),
    color: '#3C3C3C',
    fontSize: ScaleT(16),
    fontWeight: '500'
  },
  titleDotView: {
    flex: 1,
    justifyContent: 'flex-end',
    flexDirection: 'row',
    alignItems: 'center'
  },
  titleDot: {
    width: ScaleS(4),
    height: ScaleS(4),
    borderRadius: ScaleS(2),
    backgroundColor: '#666666',
    marginRight: ScaleS(4)
  },
  selfTitleLabel: {
    color: '#3C3C3C',
    fontSize: ScaleT(16),
    fontWeight: '500',
    flex: 1,
    marginBottom: ScaleS(18),
    marginTop: ScaleS(3)
  },
  photoAlbumScrollView: {
    flex: 1
  },
  itemView: {
    width: ScaleS(98),
    height: ScaleS(98),
    marginBottom: ScaleS(4)
  },
  photoImg: {
    width: ScaleS(98),
    height: ScaleS(98),
    resizeMode: 'cover'
  },
  communicateContainer: {
    width: WIDTH,
    flexDirection: 'column'
  },
  communicateLogo: {
    width: WIDTH,
    // height: ScaleS(130),
    backgroundColor: '#fff',
    opacity: 0,
    flexDirection: 'row',
    justifyContent: 'flex-end'
  },
  communicateLogoImg: {},
  communicateOutView: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    backgroundColor: '#F9F9F9',
    paddingHorizontal: ScaleS(20),
    paddingTop: ScaleS(12),
    paddingBottom: IS_IPHONEX ? ScaleS(32) : ScaleS(12)
  },
  activeTime: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  activeTimeDot: {
    width: ScaleS(6),
    height: ScaleS(6),
    marginRight: ScaleS(8),
    backgroundColor: '#FEDD00',
    borderRadius: ScaleS(3)
  },
  activeTimeText: {
    fontSize: ScaleS(13),
    fontWeight: '400',
    color: 'rgba(60,60,60,1)'
  },
  communicateShadowView: {
    width: ScaleS(254),
    height: ScaleS(50),
    shadowOffset: {
      width: ScaleS(0),
      height: ScaleS(6)
    },
    shadowColor: '#EB546B',
    shadowOpacity: 0.45,
    shadowRadius: ScaleS(29),
    borderRadius: ScaleS(25)
  },
  communicateView: {
    width: ScaleS(70),
    height: ScaleS(30),
    alignItems: 'center',
    justifyContent: 'center',
    flexDirection: 'row',
    backgroundColor: '#FFE400',
    borderRadius: ScaleS(4)
  },
  communicateLabel: {
    color: '#000000',
    fontSize: ScaleT(12),
    fontWeight: '500'
  },
  navigationBar: {
    position: 'absolute',
    right: ScaleS(5),
    top: 0,
    height: '100%',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center'
  },
  navigationImage: {
    width: ScaleS(30),
    height: ScaleS(30),
    borderRadius: ScaleS(15)
  },
  naviBtnBG: {
    marginLeft: ScaleS(8),
    width: ScaleS(58),
    height: ScaleS(28),
    backgroundColor: '#F5F5F5',
    borderRadius: ScaleS(14),
    justifyContent: 'center',
    alignItems: 'center'
  },
  naviBtnLinearGradient: {
    width: '100%',
    height: '100%',
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: ScaleS(14)
  },
  rightIcon: {
    width: ScaleS(22),
    height: ScaleS(22),
    marginRight: ScaleS(10)
  },
  rightIconText: {},
  tabContainer: {
    flexDirection: 'row',
    paddingHorizontal: ScaleS(20),
    marginTop: ScaleS(22),
    marginBottom: ScaleS(20),
    alignItems: 'center'
  },
  tabItem: {
    // marginRight: ScaleS(29)
  },
  tabLine: {
    width: ONE_PIXEL,
    height: ScaleS(10),
    backgroundColor: '#d5d5d5',
    marginHorizontal: ScaleS(20)
  },
  tabItemText: {
    fontSize: ScaleT(13),
    fontWeight: '500',
    color: '#999999'
  },
  tabItemActive: {
    color: '#3C3C3C'
  }
})
